/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package MovieListPlayer;

import Interface.AVideoDownloader;
import Interface.IDownloadProgressEvent;
import Manager.DownloaderManager;
import MovieTrees.Record.*;
import MovieTrees.Tool.*;
import PlayerComponent.JPlayerReport;
import PlayerShell.JMplayerLoader;
import VLCPlayerComponent.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.Hashtable;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JRootPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.tree.DefaultMutableTreeNode;

/**
 *
 *    @author wcss
 */
public class Players extends VLCTitleFrame implements IDownloadProgressEvent, JPlayerReport {

    public static ArrayList<MovieInfo> treeData = new ArrayList<MovieInfo>();
    private javax.swing.tree.DefaultTreeModel nodeList = null;
    private Hashtable<String, javax.swing.tree.DefaultMutableTreeNode> nodeTable = new Hashtable<String, javax.swing.tree.DefaultMutableTreeNode>();
    private VideoItem currentPlay = null;
    private Boolean canPlay = true;

    /**
     *    Creates new form Players
     */
    public Players() {
        initComponents();
        this.player.playerEvents = this;
        JMplayerLoader.MPLAYER = "mplayer";
        this.player.initPlayerWithTitle();
        this.player.showWelcome();
        this.setSize(800, 550);

        try {
            this.jtMovies.setModel(null);
            DownloaderManager.manager.createDownloader("<<movielist>>", "http://wcss2010.host019.youdnser.com/lvod/movielist/movielists.xml", "http", "", 0, 0, this);
            DownloaderManager.manager.startDownloader("<<movielist>>");
        } catch (Exception ex) {
            Logger.getLogger(Players.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    private javax.swing.tree.DefaultMutableTreeNode createSortTrees(javax.swing.tree.DefaultMutableTreeNode first, MovieInfo mi) {
        javax.swing.tree.DefaultMutableTreeNode parentNode = null;
        String nodePath = "";
        String lastNodePath = "";
        for (String s : mi.movieTreePath) {
            lastNodePath = nodePath;
            nodePath += s + "@";
            if (nodeTable.containsKey(nodePath)) {
                parentNode = nodeTable.get(nodePath);
            } else {

                javax.swing.tree.DefaultMutableTreeNode current = new javax.swing.tree.DefaultMutableTreeNode(s);

                if (parentNode != null) {
                    nodeTable.get(lastNodePath).add(current);
                    nodeTable.put(nodePath, current);
                } else {
                    nodeTable.put(nodePath, current);
                    first.add(current);
                }

                parentNode = nodeTable.get(nodePath);
            }
        }

        javax.swing.tree.DefaultMutableTreeNode movie = new javax.swing.tree.DefaultMutableTreeNode(mi.movieName);
        nodeTable.get(nodePath).add(movie);
        return movie;
    }

    /**
     *
     */
    private void uploadTrees() {
        nodeTable.clear();
        javax.swing.tree.DefaultMutableTreeNode first = new javax.swing.tree.DefaultMutableTreeNode("影片");
        nodeList = new javax.swing.tree.DefaultTreeModel(first);

        for (MovieInfo mi : treeData) {
            javax.swing.tree.DefaultMutableTreeNode node = createSortTrees(first, mi);
            if (mi.subItems.size() > 1) {
                for (VideoItem vi : mi.subItems) {
                    javax.swing.tree.DefaultMutableTreeNode video = new javax.swing.tree.DefaultMutableTreeNode(vi.videoName);
                    //video.setParent(node);
                    vi.videoDownloadType = mi.movieDownloadType;
                    vi.videoPlayMode = mi.moviePlayMode;
                    video.setUserObject(vi);
                    node.add(video);
                }
            } else 
            {
                if (mi.subItems.size() > 0)
                {
                    VideoItem vi = mi.subItems.get(0);
                    vi.videoDownloadType = mi.movieDownloadType;
                    vi.videoPlayMode = mi.moviePlayMode;
                    node.setUserObject(vi);
                }
            }
        }
        this.jtMovies.setModel(nodeList);
    }

    /**
     *    This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jSplitPane1 = new javax.swing.JSplitPane();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtMovies = new javax.swing.JTree();
        plPlayBoard = new javax.swing.JPanel();
        plState = new javax.swing.JPanel();
        lblTotal = new javax.swing.JLabel();
        lblTotalSize = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        lblCurrentSize = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        lblPercentStr = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        lblStateStr = new javax.swing.JLabel();
        btnStopAll = new javax.swing.JButton();
        player = new VLCPlayerComponent.VLCMediaPlayer();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentResized(java.awt.event.ComponentEvent evt) {
                formComponentResized(evt);
            }
        });
        addHierarchyBoundsListener(new java.awt.event.HierarchyBoundsListener() {
            public void ancestorMoved(java.awt.event.HierarchyEvent evt) {
            }
            public void ancestorResized(java.awt.event.HierarchyEvent evt) {
                formAncestorResized(evt);
            }
        });
        getContentPane().setLayout(null);

        jSplitPane1.setDividerLocation(200);
        jSplitPane1.setDividerSize(3);
        jSplitPane1.setDoubleBuffered(true);

        jtMovies.setFont(new java.awt.Font("DejaVu Sans YuanTi", 0, 18)); // NOI18N
        jtMovies.setDoubleBuffered(true);
        jtMovies.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jtMoviesMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jtMovies);

        jSplitPane1.setLeftComponent(jScrollPane1);

        plPlayBoard.setBackground(new java.awt.Color(12, 10, 7));
        plPlayBoard.setLayout(null);

        lblTotal.setText("总大小：");

        lblTotalSize.setText("0");

        jLabel2.setText("当前大小：");

        lblCurrentSize.setText("0");

        jLabel5.setText("完成度：");

        lblPercentStr.setText("0%");

        jLabel6.setText("状态：");

        lblStateStr.setText("等待");

        btnStopAll.setText("停止下载");
        btnStopAll.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnStopAllActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout plStateLayout = new javax.swing.GroupLayout(plState);
        plState.setLayout(plStateLayout);
        plStateLayout.setHorizontalGroup(
            plStateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(plStateLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblTotal)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lblTotalSize)
                .addGap(18, 18, 18)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lblCurrentSize)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel5)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lblPercentStr)
                .addGap(18, 18, 18)
                .addComponent(jLabel6)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lblStateStr)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 96, Short.MAX_VALUE)
                .addComponent(btnStopAll)
                .addGap(47, 47, 47))
        );
        plStateLayout.setVerticalGroup(
            plStateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, plStateLayout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(plStateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(lblCurrentSize)
                    .addGroup(plStateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel5)
                        .addComponent(lblPercentStr)
                        .addComponent(jLabel6)
                        .addComponent(lblStateStr)
                        .addComponent(btnStopAll))
                    .addGroup(plStateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(lblTotal)
                        .addComponent(lblTotalSize)))
                .addGap(18, 18, 18))
        );

        plPlayBoard.add(plState);
        plState.setBounds(0, 0, 607, 60);
        plPlayBoard.add(player);
        player.setBounds(0, 66, 607, 444);

        jSplitPane1.setRightComponent(plPlayBoard);

        getContentPane().add(jSplitPane1);
        jSplitPane1.setBounds(0, 0, 810, 510);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formAncestorResized(java.awt.event.HierarchyEvent evt) {//GEN-FIRST:event_formAncestorResized
        // TODO add your handling code here:
//        this.jSplitPane1.setSize(this.getSize());
//        this.jSplitPane1.invalidate();
//        this.jTree1.setSize(this.jSplitPane1.getLeftComponent().getSize());
//        this.jTree1.invalidate();
//        this.jPanel1.setSize(this.jSplitPane1.getRightComponent().getSize());
//        this.jPanel1.invalidate();
    }//GEN-LAST:event_formAncestorResized

    private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized
        // TODO add your handling code here:
        this.jSplitPane1.setLocation(0, 0);
        this.jSplitPane1.setSize(evt.getComponent().getWidth(), evt.getComponent().getHeight());
        this.jSplitPane1.updateUI();
        this.jtMovies.setSize(200, evt.getComponent().getHeight());
        this.jtMovies.updateUI();
        this.plPlayBoard.setSize(evt.getComponent().getWidth() - 200, evt.getComponent().getHeight());
        this.plPlayBoard.updateUI();
        this.plState.setSize(this.plPlayBoard.getWidth(), 60);
        this.plState.setLocation(0, 0);
        this.player.setSize(this.plPlayBoard.getWidth(), this.plPlayBoard.getHeight() - this.plState.getHeight());
        this.player.setLocation(0, 60);
        this.player.updateUI();
    }//GEN-LAST:event_formComponentResized

    private void jtMoviesMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jtMoviesMouseClicked
        // TODO add your handling code here:
        if (evt.getClickCount() == 2) {
            DefaultMutableTreeNode note = (DefaultMutableTreeNode) this.jtMovies.getLastSelectedPathComponent();
            if (note.getUserObject() != null) {
                if (note.getUserObject().getClass().getName().equals("MovieTrees.Record.VideoItem")) {
                    currentPlay = (VideoItem) note.getUserObject();
                    try {
                        DownloaderManager.manager.stopAllDownloader();
                        DownloaderManager.manager.createDownloader(currentPlay.videoName, currentPlay.videoUrl, currentPlay.videoDownloadType, "", 0, 0, this);
                        DownloaderManager.manager.startDownloader(currentPlay.videoName);
                        canPlay = true;
                    } catch (Exception ex) {
                        Logger.getLogger(Players.class.getName()).log(Level.SEVERE, null, ex);
                        javax.swing.JOptionPane.showMessageDialog(null, "对不起，开始下载视频时出错！信息：" + ex.toString());
                    }

                }
            }
        }
    }//GEN-LAST:event_jtMoviesMouseClicked

    private void btnStopAllActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnStopAllActionPerformed
        try {
            // TODO add your handling code here:
            //this.player.playMovieWithTitle("/home/wcss/.httpvideocaches/驱魔警察A/驱魔警察A_movie");
            DownloaderManager.manager.stopAllDownloader();
        } catch (Exception ex) {
            Logger.getLogger(Players.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_btnStopAllActionPerformed

    /**
     *    @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         *    Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         *    If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Players.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            Logger.getLogger(Players.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(Players.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnsupportedLookAndFeelException ex) {
            Logger.getLogger(Players.class.getName()).log(Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         *    Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new Players().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnStopAll;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JTree jtMovies;
    private javax.swing.JLabel lblCurrentSize;
    private javax.swing.JLabel lblPercentStr;
    private javax.swing.JLabel lblStateStr;
    private javax.swing.JLabel lblTotal;
    private javax.swing.JLabel lblTotalSize;
    private javax.swing.JPanel plPlayBoard;
    private javax.swing.JPanel plState;
    private VLCPlayerComponent.VLCMediaPlayer player;
    // End of variables declaration//GEN-END:variables

    @Override
    public void onReportProgress(AVideoDownloader avd, long current, long total) {
        if (!avd.downloaderID.equals("<<movielist>>")) {
            this.lblStateStr.setText("下载之中...");
            this.lblTotalSize.setText("" + avd.getTotalSize());
            this.lblCurrentSize.setText("" + avd.getCurSize());
            int percent = avd.getDownloadProgress();
            this.lblPercentStr.setText("" + percent + "%");
            if (percent >= 7) {
                if (canPlay) {
                    canPlay = false;
                    //可以播放了
                    this.player.playMovieWithTitle(avd.getVideoBufferUrl());
                }
            }
        }
    }

    @Override
    public void onReportError(AVideoDownloader avd, String string, String string1) {
        if (!avd.downloaderID.equals("<<movielist>>")) {
            this.lblStateStr.setText("下载出错！");
        }
        System.out.println(string1);
    }

    @Override
    public void onReportFinish(AVideoDownloader avd) {
        if (avd.downloaderID.equals("<<movielist>>")) {
            treeData.clear();
            treeData.addAll(MovieXMLTreeReader.readXML(avd.getVideoBufferUrl()));
            //MovieXMLTreeReader.writeXML(treeData, "/home/wcss/test.xml");
            //MovieXMLTreeReader.readXML("/home/wcss/test.xml");
            uploadTrees();
        } else {
            this.lblStateStr.setText("下载完成！");
        }
    }

    @Override
    public void onReportStatus(AVideoDownloader avd, String string) {
    }

    @Override
    public void reportPlayProgress(Object o, int i) {
    }

    @Override
    public void reportPlayAction(Object o, String string) {
    }
}
